const getQueryStringByName = function (name: string) {
  const result = location.search.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'))
  if (result == null || result.length < 1) {
    return ''
  }
  return result[1]
}

const transformData = function (data: any) {
  const params = new FormData()
  for (const item in data) {
    params.append(item, data[item])
  }
  return params
}

const DateFormat = function (date: any, fmt: string) {
  fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
  if (date === null || typeof date === 'undefined' || date === '') {
    return null
  }
  // 时间要转成obj，否则报错
  date = new Date(date)

  const o: any = {
    'M+': date.getMonth() + 1, // 月
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}
/**
 *
 * @param treeData
 * @returns 扁平化数组
 */

const treeToArray = (treeData: any) => {
  const arr: any[] = []
  const fn = (treeData: any[]) => {
    treeData.forEach((item) => {
      const tmp = { ...item }
      tmp.children = null
      arr.push(tmp.url)
      if (item.children && item.children.length > 0) {
        fn(item.children)
      }
    })
    return arr
  }
  return fn(treeData)
}

/**
 * 导出文件
 * @param file 文件
 * @param fileName 文件名
 * @param type 文件类型
 */
export const exportFile = (
  file: File,
  fileName = '文件.xls',
  type = 'application/vnd.ms-excel'
) => {
  const blob = new Blob([file], { type })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.download = fileName
  a.href = url
  a.click()
  window.URL.revokeObjectURL(url)
}

export { DateFormat, getQueryStringByName, transformData, treeToArray }
